<template>
  <div class="singer">
    <list-view @select="select" :data="singers"></list-view>
    <router-view></router-view>
  </div>
</template>

<script>
  import {getSingerList} from 'api/singer'

import Singer from 'common/js/singer'
import ListView from 'base/listview/listview'

import {mapMutations} from 'vuex'

const HOT_NAME = '热门'
const HOT_SINGER_LEN = 10

  export default {
    components: {ListView},
    data() {
      return {
        singers : []
      }
    },
    created() {
      this._getSingerList()
    },
    methods:{
      ...mapMutations({
        setSinger:'SET_SINGER'
      }),
      select(singer) {
        this.$router.push({
          path:`/singer/${singer.id}`
        })

        this.setSinger(singer)
      },
      _getSingerList() {
        getSingerList().then(res => {
          this.singers = this._serializeSinger(res.data.list)
        })
      },
      _serializeSinger(list) {
        const map = {
          hot : {
            title : HOT_NAME,
            items : []
          }
        }

        list.forEach((item, index) => {
          if (index < HOT_SINGER_LEN) {
            map.hot.items.push(new Singer(item.Fsinger_mid, item.Fsinger_name))
          }

          if (!map[item.Findex]) {
            map[item.Findex] = {
              title:item.Findex,
              items:[]
            }
          }

          map[item.Findex].items.push(new Singer(item.Fsinger_mid, item.Fsinger_name))
        })

        const hot = []
        const rest = []
        for (var key in map) {
          if (map[key].title === HOT_NAME) {
            hot.push(map[key])
          } else if (map[key].title.match(/[a-zA-Z]/)) {
            rest.push(map[key])
          }
        }

        rest.sort((v1, v2) => {
          return v1.title.charCodeAt(0) - v2.title.charCodeAt(0)
        })

        return hot.concat(rest)
      }
    }
  }
</script>

<style lang="stylus" scoped>
.singer {
  position: fixed;
  top: 88px;
  bottom: 0;
  width: 100%;
}
</style>

